<template>
    <main :style="{ left: isWideScreen ? '200px' : '0', width: isWideScreen ? 'calc(100% - 200px)' : '100%' }">
        <div>
            <h1>模型选择</h1>
            <h2>最热门</h2>
            <el-divider>
                <el-icon><star-filled /></el-icon>
            </el-divider>
            <el-carousel :interval="4000" height="250px" :type="carouselType">
                <el-carousel-item v-for="product in hottestProducts" :key="product.modelName" class="model-card-container">
                    <ModelCard :product="product" style="margin-top: 0;padding: 0;" />
                </el-carousel-item>
            </el-carousel>
            <h2>经典</h2>
            <el-divider>
                <el-icon>
                    <Menu />
                </el-icon> </el-divider>
            <div class="top-line">
                <!-- Display most starred products here -->
                <div v-for="product in classicProducts" :key="product.modelName" class="model-card-container">
                    <!-- Display individual most starred product card -->
                    <ModelCard :product="product" style="margin-right: 5%;" />

                </div>
            </div>
            <h2>全部模型</h2>
            <el-divider>
                <el-icon>
                    <Grid />
                </el-icon> </el-divider>
            <div class="product-list">
                <!-- Display product cards here -->
                <div v-for="product in productList" :key="product.modelName" class="model-card-container">
                    <!-- Display individual product card -->
                    <ModelCard :product="product" />
                </div>
            </div>
            <div class="pagination">
                <!-- Display pagination here -->
                <el-pagination v-model:current-page="currentPage" layout="prev, pager, next, jumper" :total="pageNum"
                    @current-change="changePage" :background="false" />
            </div>
        </div>
    </main>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watchEffect, onBeforeUnmount } from 'vue';
import { ElCard, ElButton, ElInput } from "element-plus";
import axios from 'axios';
import ModelCard from '../components/ModelCard.vue';
import { ElPagination, ElCarousel, ElCarouselItem } from 'element-plus';

interface SavedData {
    modelID: number;
    modelName: string;
    modelDescription: string;
    modelPrice: number;
    modelStars: number;
    modelHot: boolean;
    writer: string;
}

const message = ref('Hello, World!');
const productList = reactive<SavedData[]>([]);
const hottestProducts = reactive<SavedData[]>([]);
const classicProducts = reactive<SavedData[]>([]);
const currentPage = ref(1);
const currentHotPage = ref(1);
const currentStarPage = ref(1);
const pageNum = ref(0);
const isWideScreen = ref(false);
const screenWidth = ref(window.innerWidth);
const carouselType = ref((screenWidth.value < 1120 ? '' : 'card') as "" | "card");



isWideScreen.value = window.innerWidth >= 720;

watchEffect(() => {
    const handleResize = () => {
        isWideScreen.value = window.innerWidth >= 720;
    };

    window.addEventListener("resize", handleResize);
    return () => {
        window.removeEventListener("resize", handleResize);
    };
});
function GetCookie(name: string) {
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim();
        if (cookie.startsWith(name + '=')) {
            return cookie.substring(name.length + 1);
        }
    }
    return '';
}
function handlePageChange(page: number) {
    currentPage.value = page;
    productList.splice(0, productList.length);
    getModels(page);
};
onMounted(async () => {
    // Fetch product list using a POST request
    getModels(1);
    getHotModels(1);
    getclassicModels();
    getPageNum();
    // Sort products by hottest and most starred
}

);

const getModels = async (page: Number) => {
    let csrftoken = GetCookie('csrftoken');
    try {
        const response = await axios.post("/api/v2/normalchatgpt/getnormalmodels", {
            page: page,
        }, {
            headers: {
                'X-CSRFToken': csrftoken,
            }
        });
        if (response.data["state"] == "ok") {
            for (let i = 0; i < response.data["models"].length; i++) {
                productList.push({
                    modelID: response.data["models"][i]["modelID"],
                    modelName: response.data["models"][i]["modelName"],
                    modelDescription: response.data["models"][i]["modelDescription"],
                    modelPrice: response.data["models"][i]["modelPrice"],
                    modelStars: response.data["models"][i]["modelStars"],
                    modelHot: response.data["models"][i]["modelHot"],
                    writer: response.data["models"][i]["writer"],
                });
            }
        }
        else {
            console.log("error: " + response.data["msg"]);
        }
    } catch (error) {
        console.error('An error occurred while fetching the models:', error);
    }
};
const getHotModels = async (page: Number) => {
    let csrftoken = GetCookie('csrftoken');
    try {
        const response = await axios.post("/api/v2/normalchatgpt/getnormalhotmodel", {
            page: page,
        }, {
            headers: {
                'X-CSRFToken': csrftoken,
            }
        });
        if (response.data["state"] == "ok") {
            for (let i = 0; i < response.data["models"].length; i++) {
                hottestProducts.push({
                    modelID: response.data["models"][i]["modelID"],
                    modelName: response.data["models"][i]["modelName"],
                    modelDescription: response.data["models"][i]["modelDescription"],
                    modelPrice: response.data["models"][i]["modelPrice"],
                    modelStars: response.data["models"][i]["modelStars"],
                    modelHot: response.data["models"][i]["modelHot"],
                    writer: response.data["models"][i]["writer"],
                });
            }
        }
        else {
            console.log("error: " + response.data["msg"]);
        }
    } catch (error) {
        console.error('An error occurred while fetching the models:', error);
    }
};
const getclassicModels = async () => {
    let csrftoken = GetCookie('csrftoken');
    try {
        const response = await axios.post("/api/v2/normalchatgpt/getnormalclassicmodel", {
        }, {
            headers: {
                'X-CSRFToken': csrftoken,
            }
        });
        if (response.data["state"] == "ok") {
            for (let i = 0; i < response.data["models"].length; i++) {
                classicProducts.push({
                    modelID: response.data["models"][i]["modelID"],
                    modelName: response.data["models"][i]["modelName"],
                    modelDescription: response.data["models"][i]["modelDescription"],
                    modelPrice: response.data["models"][i]["modelPrice"],
                    modelStars: response.data["models"][i]["modelStars"],
                    modelHot: response.data["models"][i]["modelHot"],
                    writer: response.data["models"][i]["writer"],
                });
            }
        }
        else {
            console.log("error: " + response.data["msg"]);
        }
    } catch (error) {
        console.error('An error occurred while fetching the models:', error);
    }
};
const updateScreenWidth = () => {
    screenWidth.value = window.innerWidth;
    carouselType.value = screenWidth.value < 1120 ? '' : 'card';
};
const getPageNum = async () => {
    let csrftoken = GetCookie('csrftoken');
    try {
        const response = await axios.post("/api/v2/normalchatgpt/getnormalmodelpagenum", {
        }, {
            headers: {
                'X-CSRFToken': csrftoken,
            }
        });
        if (response.data["state"] == "ok") {
            pageNum.value = response.data["pageNum"];
        }
        else {
            console.log("error: " + response.data["msg"]);
        }
    } catch (error) {
        console.error('An error occurred while fetching the models:', error);
    }
};
const changePage = () => {
    productList.splice(0, productList.length);
    getModels(currentPage.value);
};
onMounted(() => {
    window.addEventListener('resize', updateScreenWidth);
});

onBeforeUnmount(() => {
    window.removeEventListener('resize', updateScreenWidth);
});


</script>

<style scoped>
/* Add your component styles here */

h1 {
    font-size: 2.5rem;
    font-weight: 700;
    margin-bottom: 1rem;
    text-align: center;
}

h2 {
    font-size: 1.5rem;
    font-weight: 700;
    margin-bottom: 1rem;
    text-align: center;
}

main {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    position: fixed;
    bottom: 0;
    left: 200px;
    width: calc(100% - 200px);

    height: calc(100% - 70px);
    overflow-y: auto;
    /* 添加一些边框和阴影 */
}

.top-line {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
}

.top-line::-webkit-scrollbar {
    display: none;
}

.product-list {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
}

.model-card-container {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 10px;
    background: transparent !important;

}

.pagination {
    margin-top: 50px;
    display: flex;

    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
}
</style>
<style>
.el-carousel__mask {
    background: transparent !important;
}

.el-divider__text {
    background-color: transparent;
    color: yellow;
}
</style>